package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.ICheckInConfigService;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-16
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private ICheckInService iCheckInService;
    @Autowired
    private ICheckInConfigService iCheckInConfigService;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 入住申请
     *
     * @param dto
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto dto) {
        //判断老人是否入住
        Elder oldElder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 1));
        if (ObjectUtil.isNotEmpty( oldElder)) {
            //说明不为空,老人已经入住
            throw new RuntimeException("该老人已入住");
        }
        //更新床位状态为已入住
       Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById( bed);
        //新增或更新老人
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
        Elder newElder = insertOrUpdateElder(bed, checkInElderDto);
        //新增签约办理
        //生成合同编号
        String contractNo = "HT" + CodeGenerator.generateContractNumber();
        insertContract(contractNo,newElder, dto);
        //新增入住信息
        CheckIn checkIn = insertCheckIn(newElder, dto);
        //新增入住配置
        insertCheckInConfig(dto, checkIn);
    }

    /**
     * 新增入住配置
     * @param dto 入住配置信息
     */
    private void insertCheckInConfig(CheckInApplyDto dto,CheckIn checkIn) {
        CheckInConfig checkInConfig = BeanUtil.toBean(dto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        iCheckInConfigService.insertCheckInConfig(checkInConfig);
    }

    /**
     * 新增入住
     * @param newElder 新增或更改的老人信息
     * @param dto 入住信息
     */
    private CheckIn insertCheckIn(Elder newElder,CheckInApplyDto dto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(newElder.getId());
        checkIn.setElderName(newElder.getName());
        checkIn.setIdCardNo(newElder.getIdCardNo());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkIn.setBedNumber(newElder.getBedNumber());
        checkIn.setStatus(0);
        iCheckInService.insertCheckIn(checkIn);
        return checkIn;
    }

    /**
     * 新增签约办理
     * @param contractNo 合约名称
     * @param newElder  老人的信息
     * @param dto 签约信息
     */
    private void insertContract(String contractNo, Elder newElder, CheckInApplyDto dto) {
         //拷贝属性
        Contract contract = BeanUtil.toBean(dto.getCheckInContractDto(), Contract.class);
        contract.setContractNumber(contractNo);
        contract.setElderId(Integer.parseInt(newElder.getId()+""));
        contract.setElderName(newElder.getName());
        //判断签约时间
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        //根据签约开始时间判断状态
       Integer status = startDate.isBefore(LocalDateTime.now())?1:0;
       contract.setStatus( status);
       contract.setStartDate(startDate);
       contract.setEndDate(endDate);
       contractMapper.insert(contract);

    }

    /**
     * 新增或更新老人
     * @param checkInElderDto 新增或更改的数据
     */
    private Elder insertOrUpdateElder(Bed bed,CheckInElderDto checkInElderDto) {
        //拷贝属性
        Elder elder = BeanUtil.toBean(checkInElderDto, Elder.class);
        //补充属性
        elder.setStatus(1);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        //查询老人信息
        Elder elder1 = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo())
                .ne(Elder::getStatus, 1)
        );
        if (ObjectUtils.isNotEmpty(elder1)) {
            //存在，老人信息存在，更新
            elderMapper.updateById(elder);
        }else {
            //不存在，新增
            elderMapper.insert(elder);
        }
        return elder;
    }


    /**
     * 入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        //查询入住信息
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        //查询老人信息
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getId, checkIn.getElderId()));
        //查询合同
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getElderId, elder.getId()));
        //查询入住配置
       CheckInConfig checkInConfig = iCheckInConfigService.select(checkIn.getId());
        //转换家属列表
        List<ElderFamilyVo> familyVoList = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);
        //整合数据返回
        CheckInDetailVo detailVo = new CheckInDetailVo();
        detailVo.setCheckInElderVo(BeanUtil.toBean(elder, CheckInElderVo.class));
        detailVo.setContract(contract);
        detailVo.setCheckInConfigVo(BeanUtil.toBean(checkInConfig, CheckInConfigVo.class));
        detailVo.setElderFamilyVoList(familyVoList);
        return detailVo;
    }
}
